/* This file is part of xREL
 *
 * Copyright (C) 2012 Timo Zimmermann <xrel@timozimmermann.de>
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Library General Public
 * License as published by the Free Software Foundation; either
 * version 2 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Library General Public License for more details.
 *
 * You should have received a copy of the GNU Library General Public License
 * along with this library; see the file COPYING.LIB.  If not, write to
 * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
 * Boston, MA 02110-1301, USA.
 */

import QtQuick 1.1
import com.nokia.meego 1.0

import "delegates"
import "components"
import "OAuth"

import "js/Core.js" as Core
import "js/HelperLib.js" as Helper
import "js/UIConstants.js" as Ui

Page {
    id: root

    tools: mainToolBar

    property string name: "SettingsPage"
    property bool loggedIn: false
    property bool credentialsAvailable: oauthToken.length > 0
    property string oauthToken: ""
    property string oauthSecret: ""

    //theme
    property bool inverted: invertedSwitch.checked
    property string primaryTextColor: inverted ? Ui.PRIMARY_TEXT_COLOR_INVERTED : Ui.PRIMARY_TEXT_COLOR
    property string secondaryTextColor: inverted ? Ui.SECONDARY_TEXT_COLOR_INVERTED : Ui.SECONDARY_TEXT_COLOR
    property string titleBackgroundColor: inverted ? Ui.TITLE_BACKGROUND_COLOR_INVERTED : Ui.TITLE_BACKGROUND_COLOR
    property string backgroundColor: inverted ? Ui.BACKGROUND_COLOR_INVERTED : Ui.BACKGROUND_COLOR

    function update() {
        var credentials = Core.getCredentials();
        oauthToken = credentials["token"];
        oauthSecret = credentials["secret"];

        var settings = Core.getSettings();
        loggedIn = settings["loggedIn"] && credentialsAvailable;

        theme.inverted = inverted;
    }

    function save() {
        var settings = new Object;
        settings["loggedIn"] = loggedIn;

        Core.saveSettings(settings);
    }

    OAuthXmlListModel {
        id: oauthUserListModel

        oauthSource: "http://api.xrel.to/api/user/get_authd_user.xml"
        query: "/user"
        token: globalSettings.oauthToken
        secret: globalSettings.oauthSecret

        XmlRole { name: "id"; query: "id/string()" }
        XmlRole { name: "name"; query: "name/string()" }
        XmlRole { name: "secret"; query: "title/string()" }
        XmlRole { name: "locale"; query: "secret/string()" }
        XmlRole { name: "avatar_url"; query: "avatar_url/string()" }
        XmlRole { name: "avatar_thumb_url"; query: "avatar_thumb_url/string()" }
    }

    OAuthXmlListModel {
        id: oauthLimitListModel

        oauthSource: "http://api.xrel.to/api/user/rate_limit_status.xml"
        query: "/rate_limit_status"
        token: globalSettings.oauthToken
        secret: globalSettings.oauthSecret

        XmlRole { name: "remaining_calls"; query: "remaining_calls/number()" }
        XmlRole { name: "reset_time_u"; query: "reset_time_u/number()" }
        XmlRole { name: "reset_time"; query: "reset_time/string()" }
    }

    XmlListModel {
        id: limitListModel

        source: "http://api.xrel.to/api/user/rate_limit_status.xml"
        query: "/rate_limit_status"

        XmlRole { name: "remaining_calls"; query: "remaining_calls/number()" }
        XmlRole { name: "reset_time_u"; query: "reset_time_u/number()" }
        XmlRole { name: "reset_time"; query: "reset_time/string()" }
    }

    PageBackground { }

    QueryDialog {
        id: clearQuery
        acceptButtonText: qsTr("Clear")
        rejectButtonText: qsTr("Logout")
        message: qsTr("Do you want to clear the credential data or logout?")
        titleText: qsTr("Logout")
        onAccepted: {
            Core.clearCredentials();
            globalSettings.update();
        }
        onRejected: ;
    }

    Flickable {
        anchors.top: pageHeader.bottom
        anchors.left: parent.left
        anchors.right: parent.right
        anchors.bottom: parent.bottom
        contentHeight: childrenRect.height
        clip: true

        Column {
            id: contentColumn
            anchors.fill: parent
            spacing: 0

            Connections {
                target: credentialsSwitch
                onCheckedChanged: globalSettings.loggedIn = credentialsSwitch.checked
            }

            SectionLabel { text: qsTr("Theme") }
            SectionEntrySwitch {
                id: invertedSwitch
                titleText: "Inverted"
                checked: true
                onCheckedChanged: theme.inverted = invertedSwitch.checked;
            }

            SectionLabel { text: qsTr("OAuth authentification") }
            SectionEntrySwitch {
                id: credentialsSwitch
                titleText: "xREL credentials"
                checked: globalSettings.credentialsAvailable && globalSettings.loggedIn
                onClicked: {
                    if(globalSettings.credentialsAvailable && globalSettings.loggedIn)
                        clearQuery.open();
                    else if(!globalSettings.credentialsAvailable)
                        pageStack.push(Qt.resolvedUrl("OAuthPage.qml"));

                }
            }

            SectionLabel { id: accountLabel; text: qsTr("Account information"); opacity: 0.0}
            Item {
                id: accountInfo
                width: parent.width
                height: childrenRect.height
                opacity: 0.0
                Repeater {
                    width: parent.width
                    model: oauthUserListModel
                    delegate: AccountInfoDelegate { }
                }
            }

            SectionLabel { text: qsTr("Request limit") }
            Item {
                id: userLimit
                width: parent.width
                height: childrenRect.height
                opacity: 0.0
                Repeater {
                    model: oauthLimitListModel
                    delegate: RequestLimitDelegate { limitType: "User" }
                }
            }
            Item {
                id: ipLimit
                width: parent.width
                height: childrenRect.height
                Repeater {
                    model: limitListModel
                    delegate: RequestLimitDelegate { limitType: "IP" }
                }
            }
        }
    }

    PageHeader {
        id: pageHeader
        text: qsTr("Settings")
    }

    transitions: Transition {
        AnchorAnimation { easing.type: Easing.OutBounce }
        NumberAnimation { properties: "y"; easing.type: Easing.OutBounce }
        NumberAnimation { properties: "opacity"; easing.type: Easing.InOutQuad }
        ScriptAction { scriptName: "reloadUserList" }
        ScriptAction { scriptName: "reloadLimitList" }
    }

    states: [
        State {
            name: "LOGGED_IN"
            when: credentialsSwitch.checked && status === PageStatus.Active
            StateChangeScript { name: "reloadUserList"; script: oauthUserListModel.reload(); }
            StateChangeScript { name: "reloadLimitList"; script: oauthLimitListModel.reload(); }
            PropertyChanges { target: accountLabel; opacity: 1.0 }
            PropertyChanges { target: accountInfo; opacity: 1.0 }
            PropertyChanges { target: userLimit; opacity: 1.0 }
        }
    ]

    Component.onCompleted: {
        Core.openDB();
        update();
    }

    Component.onDestruction: {
        save();
    }
}
